<?php


namespace App\PubApi\Model;


use App\Facades\Captcha;
use App\Service\Sms;
use App\Service\WeApp;
use EchoPHP\Facades\Db;
use EchoPHP\Facades\Redis;

class VideoInterview {

    private $roomStartTime;
    private $roomEndTime;

    public function __construct() {
        $this->roomStartTime = date('Y-m-d', time()) . ' 00:00:00';
        if (config('xcx.onlylogintoday', true)) {
            $this->roomEndTime = date('Y-m-d', time()) . ' 23:59:59';
        } else {
            $this->roomEndTime = date('Y-m-d', strtotime('+30 days')) . ' 23:59:59';
        }
    }

    /**
     * 获取登录凭据
     * @param $code
     * @return mixed
     * @throws \Exception
     */
    public function getLoginInfo($code) {
        try {
            $appId = config('xcx.videointerview.appid');
            $secret = config('xcx.videointerview.secret');
        } catch (\Exception $e) {
            $appId = $secret = '';
        }

        if (empty($code) || empty($appId) || empty($secret)) {
            $loginInfo = [];
        } else {
            $weApp = new WeApp($appId, $secret);
            $loginInfo = $weApp->getLoginInfo($code);
        }
        return $loginInfo;
    }

    /**
     * 根据用户的openid获取系统内绑定的账号信息（手机号）
     * @param $openId
     * @return mixed
     */
    public function getUserInfoByOpenId($openId) {
        $sql = 'SELECT openid,mobilephone FROM WeAppBind WHERE openid=? AND status=? ORDER BY createdate DESC';
        $var = [$openId, '01'];

        return Db::connect()->selectOne($sql, $var);
    }

    /**
     * 根据手机号查询绑定的用户信息
     * @param $phone
     * @return mixed
     */
    public function getUserInfoByPhone($phone) {
        $sql = 'SELECT openid,mobilephone FROM WeAppBind WHERE mobilephone=? AND status=? ORDER BY createdate DESC';
        $var = [$phone, '01'];

        return Db::connect()->selectOne($sql, $var);
    }

    /**
     * 发送短信登陆验证码
     * @param $uuid
     * @param $captchaCode
     * @param $mobilePhone
     * @return array
     * @throws \GuzzleHttp\Exception\GuzzleException
     * @throws \Exception
     */
    public function sendMpCode($uuid, $captchaCode, $mobilePhone) {
        $action = '_bind';
        //图形验证码校验
        $result = Captcha::check('image', ($uuid . $action), $captchaCode);

        if (!$result) {
            return ['error' => -1, 'message' => '验证码错误,请重新输入'];
        }

        $verifyCode = Captcha::generate('phone', $mobilePhone . $action);
        if ($verifyCode['error'] != 0) {
            return ['error' => -2, 'message' => '发送验证码出现错误', 'verifyerror' => $verifyCode];
        }
        //发送验证码
        $sms = new Sms();
        $channel = config('app.sms.channel.account');
        $content = '欢迎绑定无忧RPO微信小程序，验证码为' . $verifyCode['code'] . ',有效时间' . floor($verifyCode['expire'] / 60) . '分钟。请勿泄露给他人';
        $result = $sms->send($mobilePhone, $content, $channel);
        if ($result) {
            return ['error' => 0, 'message' => '短信发送成功'];
        }
        return ['error' => -3, 'message' => '短信发送失败'];
    }

    /**
     * 绑定用户手机
     * @param $openId
     * @param $mobilePhone
     * @param $verifyCode
     * @return array
     */
    public function bindUserInfo($openId, $mobilePhone, $verifyCode) {
        $result = Captcha::check('phone', $mobilePhone . '_bind', $verifyCode);
        if (!$result) {
            return ['error' => -1, 'message' => '验证码错误,请重新输入'];
        }
        $userInfo = $this->getUserInfoByOpenId($openId);
        if (!empty($userInfo) && $userInfo['mobilephone'] == $mobilePhone) {
            return ['error' => 0, 'message' => '绑定成功'];
        } elseif (!empty($userInfo)) {
            return ['error' => -2, 'message' => '已绑定其他手机号'];
        }

        $userInfo = $this->getUserInfoByPhone($mobilePhone);
        if (!empty($userInfo)) {
            return ['error' => -4, 'message' => '该手机号已被使用'];
        }


        $sql = 'INSERT INTO WeAppBind(openid,mobilephone,status,createdate,updatedate) VALUE(?,?,?,Now(), Now())';
        $var = [$openId, $mobilePhone, '01'];
        $result = Db::connect()->insert($sql, $var);
        if (!$result) {
            return ['error' => -3, 'message' => '系统繁忙，请稍后再试'];
        }
        return ['error' => 0, 'message' => '绑定成功'];
    }

    /**
     * 解绑手机号
     * @param $openId
     * @return array
     */
    public function unbindUserInfo($openId) {
        $sql = 'UPDATE WeAppBind SET status=?,updatedate=Now() WHERE openid=? AND status=?';
        $var = ['06', $openId, '01'];
        Db::connect()->update($sql, $var);
        return ['status' => 0, 'message' => '解绑成功'];
    }

    /**
     * 获取房间列表
     * @param $mobilePhone
     * @param $userType 用户身份 1-求职者 0-面试官
     * @return array|bool|mixed
     * @throws \Exception
     */
    public function getRoomListByPhone($mobilePhone, $userType) {
        if ($userType == 1) {
            //查询求职者身份下的房间列表
            $roomList = $this->getJobSeekerRoomListByPhone($mobilePhone);
        } else {
            //查询面试官身份下的房间列表
            $roomList = $this->getInterviewerRoomListByPhone($mobilePhone);
        }

        foreach ($roomList as &$item) {
            //查询在线候选人数量  $key = 'ROOM:' . $roomNum . ':OL:' . $userType;
            $redisKey = 'ROOM:' . $item['roomnum_out'] . ':LOGGED';
            $item['onlineseeker'] = Redis::connect('videointerview')->sCard($redisKey);
        }

        return $roomList;
    }

    /**
     * 根据手机号查询求职者房间列表
     * @param $mobilePhone
     * @return array
     * @throws \Exception
     */
    public function getJobSeekerRoomListByPhone($mobilePhone) {
        $sql = 'select 1 as usertype,user.authorizecode_out as verifycode,user.starttime,Room.roomid,Room.roomid_out,Room.roomnum_out,Room.roomname,Room.starttime as roomstarttime,Room.endtime as roomendtime  from RoomJobseeker user LEFT JOIN Room ON user.roomid=Room.roomid WHERE user.mobilephone=? AND user.status=? AND user.starttime BETWEEN ? AND ? ORDER BY starttime ASC, Room.roomid ASC';
        $var = [$mobilePhone, '03', $this->roomStartTime, $this->roomEndTime];

        return Db::connect()->select($sql, $var, 0, 200);
    }

    /**
     * 根据手机号查询面试官身份房间列表
     * @param $mobilePhone
     * @return array
     * @throws \Exception
     */
    public function getInterviewerRoomListByPhone($mobilePhone) {
        $sql = 'select 0 as usertype,user.authorizecode_out as verifycode,user.starttime,Room.roomid,Room.roomid_out,Room.roomnum_out,Room.roomname,Room.starttime as roomstarttime,Room.endtime as roomendtime  from RoomInterviewer user LEFT JOIN Room ON user.roomid=Room.roomid WHERE user.mobilephone=? AND user.status=? AND user.starttime BETWEEN ? AND ? ORDER BY starttime ASC,Room.roomid ASC';
        $var = [$mobilePhone, '03', $this->roomStartTime, $this->roomEndTime];

        return Db::connect()->select($sql, $var, 0, 200);
    }

}